package com.yootk.servlet;

import com.yootk.dbc.DatabaseConnection;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * 异步数据验证
 */
@WebServlet("/check.action")
public class CheckServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        String mid = req.getParameter("mid"); // 接收用户名
        String sql = "SELECT COUNT(*) FROM member WHERE mid=?"; // 查询SQL语句
        boolean flag = false; // 不可以使用
        try {
            PreparedStatement pstmt = DatabaseConnection.getConnection().prepareStatement(sql);
            pstmt.setString(1, mid); // 设置用户名
            ResultSet rs = pstmt.executeQuery(); // 数据查询
            if (rs.next()) {
                long count = rs.getLong(1); // 获取个数
                if (count == 0) {
                    flag = true; // 允许使用
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DatabaseConnection.close();
        }
        resp.getWriter().print(flag);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
